package com.jiepos.mpos.inter.push.jiguang;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.jiepos.mpos.core.util.StringUtils;
import com.jiepos.mpos.inter.push.IMposPush;
import com.jiepos.mpos.inter.push.MposPush;

import cn.jiguang.common.ClientConfig;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;

/**
 * @ClassName: JGPushService
 * @Description: 极光推送服务实现
 * @author 孙永
 * @date 2017年11月3日 下午6:50:21
 */
@Component
public class JGPushService implements IMposPush{
	
	@Autowired
	private JGPush JGPush;
	
	private static Logger logger = LoggerFactory.getLogger(JGPushService.class);
	
	@Override
	public void pushSingleById(MposPush mposPush, String clientId, String title, String alert){
		pushSingleById(mposPush, clientId, title, alert, null);
	}
	
	@Override
	public void pushSingleById(MposPush mposPush, String clientId, String title, String alert, Map<String, String> extras){
		pushSingle(mposPush, clientId, null, title, alert, extras);
	}
	
	@Override
	public void pushSingleByAlias(MposPush mposPush, String alias, String title, String alert){
		pushSingleByAlias(mposPush, alias, title, alert, null);
	}
	
	@Override
	public void pushSingleByAlias(MposPush mposPush, String alias, String title, String alert, Map<String, String> extras){
		pushSingle(mposPush, null, alias, title, alert, extras);
	}
	
	@Override
	public void pushSingle(MposPush mposPush, String clientId, String alias, String title, String alert){
		pushSingle(mposPush, clientId, alias, title, alert, null);
	}
	
	@Override
	public void pushListByIds(MposPush mposPush, List<String> clientIds, String title, String alert){
		pushListByIds(mposPush, clientIds, title, alert, null);
	}
	
	@Override
	public void pushListByIds(MposPush mposPush, List<String> clientIds, String title, String alert, Map<String, String> extras){
		pushList(mposPush, clientIds, null, title, alert, extras);
	}
	
	@Override
	public void pushListByAlias(MposPush mposPush, List<String> aliases, String title, String alert){
		pushListByAlias(mposPush, aliases, title, alert, null);
	}

	@Override
	public void pushListByAlias(MposPush mposPush, List<String> aliases, String title, String alert, Map<String, String> extras){
		pushList(mposPush, null, aliases, title, alert, extras);
	}
	
	@Override
	public void pushList(MposPush mposPush, List<String> clientIds, List<String> aliases, String title, String alert){
		pushList(mposPush, clientIds, aliases, title, alert, null);
	}
	
	@Override
	public void pushApp(MposPush mposPush, String title, String alert){
		pushApp(mposPush, title, alert, null);
	}
	
	@Override
	public void pushApp(MposPush mposPush, String title, String alert, Map<String, String> extras){
		pushMessage(mposPush, null, null, title, alert, extras);
	}
	
	@Override
	public void pushSingle(MposPush mposPush, String registrationId, String alias, String title, String alert, Map<String, String> extras){
		if(StringUtils.isBlank(registrationId) && StringUtils.isBlank(alias)){
			logger.warn("单用户推送注册ID或者别名为空");
			return;
		}
		List<String> registrationIds = new ArrayList<>(), aliasList = new ArrayList<>();
		if(!StringUtils.isBlank(registrationId)){
			registrationIds.add(registrationId);
		}
		if(!StringUtils.isBlank(alias)){
			aliasList.add(alias);
		}
		pushList(mposPush, registrationIds, aliasList, title, alert, extras);
	}
	
	@Override
	public void pushList(MposPush mposPush, List<String> clientIds, List<String> alias, String title, String alert, Map<String, String> extras){
		if((clientIds == null || clientIds.isEmpty()) && (alias == null || alias.isEmpty())){
			logger.warn("批量用户推送注册ID或者别名为空");
			return;
		}
		pushMessage(mposPush, clientIds, alias, title, alert, extras);
	}
	
	/**
	 * 推送消息
	 * @param mposPush
	 * @param registrationIds 注册ID集合
	 * @param aliases 别名集合
	 * @param title 标题
	 * @param alert 内容
	 * @param msgContent 透传内容
	 */
	private void pushMessage(MposPush mposPush, List<String> clientIds, List<String> aliases, String title, String alert, Map<String, String> extras){
		try {
			/*基本校验*/
			if(mposPush == null || StringUtils.isBlank(mposPush.getAppKey()) || StringUtils.isBlank(mposPush.getMasterSecret())){
				logger.warn("APP推送秘钥丢失");
				return;
			}
			/*加载推送对象*/
			PushPayload pushPayload = PushPayload
					.newBuilder()
					.setPlatform(getPlatform())
					.setAudience(getAudience(clientIds, aliases))
					.setNotification(getNotification(title, alert, extras))
					.setOptions(getOptions()).build();
			/*客户端配置*/
			ClientConfig config = ClientConfig.getInstance();
			config.setTimeToLive(JGPush.getTimeToLive());
			/*推送*/
			JPushClient client = new JPushClient(mposPush.getMasterSecret(), mposPush.getAppKey(), null, config);
			PushResult result = client.sendPush(pushPayload);
			logger.info("推送结果：{}", result.toString());
		} catch (Exception e) {
			logger.info("推送失败");
			e.printStackTrace();
		}
	}
	
	/**
	 * 定义推送平台
	 * @return
	 */
	private Platform getPlatform(){
		return Platform.android_ios();
	}
	
	/**
	 * 组装推送目标
	 * @param registrationIds 注册ID集合
	 * @param aliases 别名集合
	 * @return
	 */
	private Audience getAudience(List<String> registrationIds, List<String> aliases){
		if((registrationIds == null || registrationIds.isEmpty()) && (aliases == null || aliases.isEmpty())){
			return Audience.all();
		}else if(aliases == null || aliases.isEmpty()){
			return Audience.registrationId(registrationIds);
		}else if(registrationIds == null || registrationIds.isEmpty()){
			return Audience.alias(aliases);
		}else{
			return Audience.newBuilder()
					.addAudienceTarget(AudienceTarget.registrationId(registrationIds))
					.addAudienceTarget(AudienceTarget.alias(aliases))
					.build();
		}
	}
	
	/**
	 * 组装推送内容
	 * @param title 推送标题
	 * @param alert 推送内容
	 * @param extras 额外参数
	 * @return
	 */
	private Notification getNotification(String title, String alert, Map<String, String> extras){
		return Notification.newBuilder()
				.addPlatformNotification(AndroidNotification
						.newBuilder().setTitle(title)
						.setAlert(alert)
						.addExtras(extras).build())
				.addPlatformNotification(IosNotification
						.newBuilder()
						.setAlert(alert)
						.addExtras(extras).build()).build();
	}
	
	/**
	 * 组装透传内容
	 * @param msgContent 透传内容
	 * @return
	 */
	private Message getMessage(String msgContent){
		if(!StringUtils.isBlank(msgContent)){
			return Message.content(msgContent);
		}
		return null;
	}
	
	/**
	 * 组装其它设置参数
	 * @return
	 */
	private Options getOptions(){
		return Options.newBuilder().setTimeToLive(JGPush.getTimeToLive()).build();// 设置消息离线时长
	}
}
